package team.bluepen.supermarket.web.filter;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.data.entity.User;
import team.bluepen.supermarket.util.Log;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录检验过滤器
 * @author Kai
 */
@WebFilter(filterName = "LoginFilter", urlPatterns = {"*.jsp", "/api/"})
public class LoginFilter implements Filter {
    private static final String TAG = "LoginFilter";

    public void init(FilterConfig config) throws ServletException {
        Log.i(TAG, "Filter Loading Successful.");
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String url = req.getRequestURI();
        // 获取Url
        String endWith = url.substring(url.lastIndexOf('/') + 1);
        if (!endWith.equals("") && !endWith.equals("/")
                && !endWith.equals("register.jsp") && !endWith.equals("/register.jsp")) {
            if (checkLoginState(req)) {
                chain.doFilter(request, response);
            } else {
                resp.sendRedirect("/");
            }
        } else {
            if (checkLoginState(req)) {
                resp.sendRedirect("/overview.jsp");
            } else {
                chain.doFilter(request, response);
            }
        }
    }

    /**
     * 检查是否有登录信息
     */
    private boolean checkLoginState(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        return user != null;
    }
}
